package com.bnpparibas.tools.ant.logic.query;

import java.awt.*;
import java.awt.event.*;

import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;

public class QueryTask extends Task {
	private String name;
	private String message;
	private String value;

	private boolean password;
	private boolean override;
	private boolean useDefault = false;
	private boolean cancelled;

	public void setName(String name) {
		this.name = name;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
	
	public void setPassword(boolean password) {
		this.password = password;
	}
	
	public void setOverride(boolean override) {
		this.override = override;
	}
	
	public void setValue(String value) {
		this.value = value;
		this.useDefault = true;
	}
	
	public void execute() throws BuildException {
		if (name == null) {
			throw new BuildException("<query> task requires 'name=' attribute.");
		}

		cancelled = false;

		Frame hiddenFrame = new Frame("Ant Query Task Hidden Frame");
		final Dialog dialog = new Dialog(hiddenFrame, "Ant Query", true);
		dialog.setLocation(100,100);
		dialog.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent windowEvent) {
				cancelled = true;
				dialog.dispose();
			} 
		});
		Panel buttonPanel = new Panel();

		if (message == null) {
			message = name;
		}
		Label label = new Label(message);
		
		final TextField textField = new TextField(16);
		if (password) {
			textField.setEchoChar('*');
		}
		if (useDefault) {
			textField.setText(value);
		}
		textField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				value = textField.getText();
				dialog.dispose();
			}
		});

		Button okButton = new Button("Ok");
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				value = textField.getText();
				dialog.dispose();
			}
		});
		
		Button cancelButton = new Button("Cancel");
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				cancelled = true;
				dialog.dispose();
			}
		});
		
		buttonPanel.add(okButton);
		buttonPanel.add(cancelButton);
		
		dialog.add(label, "North");
		dialog.add(textField, "Center");
		dialog.add(buttonPanel, "South");
		dialog.pack();
		
		dialog.show();
		hiddenFrame.dispose();

		if (cancelled) {
			throw new BuildException("Cancelled by user.");
		}
		if (value != null) {
			getProject().setProperty(name, value);
		}
	}
}
